package com.duan.laugh.common.security.util;


import cn.hutool.core.util.StrUtil;
import com.duan.laugh.common.security.constants.SecurityConstants;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户工具类
 *
 * @author duanjw
 */
@UtilityClass
public class UserUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return LaughUser
     * <p>
     */
    public LaughUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof LaughUser) {
            // 同时放到ttl中
            final LaughUser laughUser = (LaughUser) principal;
            UserContextHolder.set(laughUser);
            return laughUser;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public LaughUser getUser() {
        // ttl中有用户直接返回
        final LaughUser laughUser = UserContextHolder.get();
        if (null != laughUser) {
            return laughUser;
        }
        Authentication authentication = getAuthentication();
        return getUser(authentication);
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<Integer> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<Integer> roleIds = new ArrayList<>();
        authorities.stream()
                .filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE))
                .forEach(granted -> {
                    String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE);
                    roleIds.add(Integer.parseInt(id));
                });
        return roleIds;
    }

    /**
     * 获取客户端
     *
     * @return clientId
     */
    public String getClientId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }

    /**
     * 获取token
     * @return
     */
    public String getToken(){
        return ((OAuth2AuthenticationDetails)getAuthentication().getDetails()).getTokenValue();
    }

}
